
const Koa = require('koa');
const app = new Koa();

app.use(async(ctx) =>{
    //先模拟路由判断,Get => 显示表单,POST =>提交,其他=> 404
    if(ctx.url === '/' && ctx.method ==='GET'){
        //显示表单
        let html = `
                <h1>JSPang Koa2 request Post!</h1>
                <form method = 'POST' action=''>
                    <p>userName</p>
                    <input name="username" /><br/>
                    <p>age</p>
                    <input name="age" /><br/>
                    <p>website</p>
                    <input name="website" /><br/>
                    <button type = "submit">submit</button>
                </form>
        `;

        ctx.body = html;

    }else if (ctx.url === '/' && ctx.method ==='POST'){
        let postdata = await paresePostData(ctx);
        ctx.body = postdata;
    }
    else
    {
        ctx.body = '<h1>404!</h1>';
    }   

});


function paresePostData(ctx){
    return new Promise((resolve,reject) =>{
        try{
            let postdata = "";
            //原生的方法接受变量
            ctx.req.addListener('data',(data) =>{
                postdata += data;
            })
            //koa2的方法
            ctx.req.on('end',function(){
                let parseData = parseQueryStr(postdata);

                resolve(parseData);
            })
        }catch(error){
            reject(error);
        }
    })
}

function parseQueryStr(queryStr){
    let queryData = {};

    //先将URL参数按照&来拆分
    let queryStrList = queryStr.split('&');
    console.log(queryStrList);
    console.log(queryStrList.entries());

    for(let [index,queryStr] of queryStrList.entries()){
        //再将URL参数按照=拆分
        let itemList = queryStr.split('=');
        console.log(itemList);
        queryData[itemList[0]] = decodeURIComponent(itemList[1]);
    }

    return queryData

}

app.listen(3000,() =>{
     
    console.log('[demo] server is starting at port 3000!');
    
})